#define BUFFER_SIZE 4096

class FYL_Socket
{

	private:
		s32 fd_socket;

	public:
		FYL_Socket(std::string*, u32);

		s32 createSocket();
		bool connect(std::string*, u32);
		void close();
		u32 write(std::string*);
		u32 write(char*);
		std::string read();

};

FYL_Socket::FYL_Socket(std::string *host, u32 port)
{

	createSocket();
	connect(host, port);

}

s32 FYL_Socket::createSocket()
{

	fd_socket = net_socket(AF_INET, SOCK_STREAM, 0);
	return (fd_socket);

}

bool FYL_Socket::connect(std::string *host, u32 port)
{

	if (fd_socket < 0)
		return (false);

	if ((port < 0) || (port > 65535))
		return (false);

	struct hostent *hostinfo = net_gethostbyname((char *) host->c_str());

	if (hostinfo == NULL)
		return (false);

	struct sockaddr_in serv_addr;

	bzero((char *) &serv_addr, sizeof(serv_addr));

	serv_addr.sin_family = AF_INET;
	bcopy((char *) hostinfo->h_addr_list[0], (char *) &serv_addr.sin_addr.s_addr, hostinfo->h_length);
	serv_addr.sin_port = htons(port);

	if (net_connect(fd_socket, (sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
		return (false);

	return (true);

}

void FYL_Socket::close()
{

	net_close(fd_socket);

}

u32 FYL_Socket::write(std::string* message)
{

	return (write((char *) message->c_str()));

}

u32 FYL_Socket::write(char *message)
{

	if (fd_socket < 0)
		return (0);

	if (message == NULL)
		return (0);

	char *buffer = new char [BUFFER_SIZE];
	u32 count = 0, size = strlen(message);

	while (count < size)
	{

		bzero(buffer, BUFFER_SIZE);
		strncpy(buffer, message, BUFFER_SIZE);

		if (net_write(fd_socket, buffer, BUFFER_SIZE) < 0)
			return (count);

		count += BUFFER_SIZE;
		message += BUFFER_SIZE;

	}

	return (size);

}

std::string FYL_Socket::read()
{

	std::string message;

	if (fd_socket < 0)
		return (message);

	char *buffer = new char [BUFFER_SIZE];
	bzero(buffer, BUFFER_SIZE);

	while (net_read(fd_socket, buffer, BUFFER_SIZE) != 0)
	{

		message.append(buffer);
		bzero(buffer, BUFFER_SIZE);
	}

	message.append(buffer);
	return (message);

}
